package com.graduate.emos.wx.config.xss;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HtmlUtil;
import cn.hutool.json.JSONUtil;


import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Set;

//抵御xss攻击，对参数进行转义
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
    //必须定义有参构造方法接收请求参数对象
    public XssHttpServletRequestWrapper(HttpServletRequest request) {
        super(request);
    }

    @Override
    public String getParameter(String name) {
        //获取请求参数
        String param = super.getParameter(name);
        if (!StrUtil.hasEmpty(param)){
            //如果获取的参数不为空将其转义
            param = HtmlUtil.filter(param);
        }
        return param;
    }

    @Override
    public String[] getParameterValues(String name) {
        //获取参数数组
        String[] params =  super.getParameterValues(name);
        if (params != null){
            //遍历数组进行转义
            for (int i = 0; i < params.length; i++) {
                if (!StrUtil.hasEmpty(params[i])){
                    params[i] = HtmlUtil.filter(params[i]);
                }
            }
        }
        return params;
    }

    @Override
    public Map<String, String[]> getParameterMap() {
        //获取参数map
        Map<String,String[]> paramMap = super.getParameterMap();
        if (paramMap != null){
            //得到所有的key
            Set<String> keys = paramMap.keySet();
            for (String key : keys) {
                //根据key遍历map转义
                String[] values = paramMap.get(key);
                if (values != null){
                    for (int i = 0; i < values.length; i++) {
                        if (!StrUtil.hasEmpty(values[i])){
                            values[i] = HtmlUtil.filter(values[i]);
                        }
                    }
                    paramMap.put(key,values);
                }
            }
        }
        return paramMap;
    }

    @Override
    public String getHeader(String name) {
        //获取请求头
        String header = super.getHeader(name);
        //转义
        if (!StrUtil.hasEmpty(header)){
            HtmlUtil.filter(header);
        }
        return header;
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        //读取内容
        InputStream in = super.getInputStream();
        InputStreamReader reader = new InputStreamReader(in, StandardCharsets.UTF_8);
        BufferedReader buffer = new BufferedReader(reader);
        StringBuffer body = new StringBuffer();
        String line = buffer.readLine();
        while(line != null){
            body.append(line);
            line = buffer.readLine();
        }
        //读取完成后关闭io流
        buffer.close();
        reader.close();
        in.close();
        //解析成map对象
        Map<String,Object> map = JSONUtil.parseObj(body.toString());
        //遍历转义
        for (String key : map.keySet()) {
            Object val = map.get(key);
            if (val instanceof String && !StrUtil.hasEmpty(val.toString())){
                map.put(key,HtmlUtil.filter(val.toString()));
            }
        }
        //将map转成json
        String jsonStr = JSONUtil.toJsonStr(map);
        //将json字符串装到IO流中返回
        ByteArrayInputStream bais = new ByteArrayInputStream(jsonStr.getBytes());
        return new ServletInputStream() {
            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }

            @Override
            public int read() throws IOException {
                return bais.read();
            }
        };
    }
}
